<template>
    <div class="product-list-container">
        <div class="content-wrapper">
            <div class="header-section" v-if="commoditys.classification">
                <div class="category-header">
                    <h2 class="category-title">{{ commoditys.classification }}</h2>
                    <p class="category-subtitle">精选优质商品，品质保证</p>
                </div>
                <div class="product-stats">
                    <span class="stat-item">
                        <i class="el-icon-goods"></i>
                        {{ commoditys.commodity?.length || 0 }} 件商品
                    </span>
                </div>
            </div>
            
            <div class="products-grid" v-if="commoditys.commodity && commoditys.commodity.length > 0">
                <div 
                    class="product-card" 
                    v-for="commodity in commoditys.commodity" 
                    :key="commodity.id"
                    @click="goToDetail(commodity.id)"
                >
                    <div class="product-image">
                        <img 
                            v-if="getProductImageUrl(commodity)"
                            :src="getProductImageUrl(commodity)" 
                            :alt="commodity.name"
                            @error="handleImageError"
                        />
                        <div v-else class="no-image-placeholder">
                            <i class="el-icon-picture-outline"></i>
                            <span>暂无图片</span>
                        </div>
                        <div class="no-image-placeholder" style="display: none;">
                            <i class="el-icon-picture-outline"></i>
                            <span>图片加载失败</span>
                        </div>
                        <div class="product-overlay">
                            <el-button 
                                type="primary" 
                                size="small" 
                                @click.stop="addToCart(commodity)"
                                class="add-cart-btn"
                            >
                                <i class="el-icon-shopping-cart-2"></i>
                                加入购物车
                            </el-button>
                        </div>
                    </div>
                    
                    <div class="product-content">
                        <div class="product-price">
                            ￥{{ commodity.price }}
                        </div>
                        
                        <h3 class="product-name">
                            {{ commodity.name }}{{ commodity.caption }}
                        </h3>
                        
                        <div class="product-meta">
                            <div class="meta-item">
                                <i class="el-icon-chat-dot-square"></i>
                                {{ commodity.comments || 0 }} 条评价
                            </div>
                            <div class="meta-item brand">
                                <i class="el-icon-medal"></i>
                                {{ commodity.brand || '其他品牌' }}
                            </div>
                        </div>
                        
                        <div class="product-actions">
                            <el-tag 
                                v-if="commodity.stock > 0" 
                                type="success" 
                                size="small"
                                class="stock-tag"
                            >
                                现货
                            </el-tag>
                            <el-tag 
                                v-else 
                                type="danger" 
                                size="small"
                                class="stock-tag"
                            >
                                缺货
                            </el-tag>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="empty-state" v-else>
                <el-empty 
                    description="暂无商品" 
                    :image-size="200"
                >
                    <template #description>
                        <p>该分类下暂时没有商品</p>
                        <p>请关注我们的最新上架信息</p>
                    </template>
                </el-empty>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { getClassificationsCommodity, createCart } from '@/api/shopping'
import { useRoute, useRouter } from "vue-router"
import { ElMessage } from 'element-plus'

const route = useRoute()
const router = useRouter()

const commoditys = ref({
    commodity: [],
    classification: ''
})

// 获取分类商品
const fetchCommodityList = async () => {
    try {
        const data = await getClassificationsCommodity(route.params.id)
        commoditys.value = data
    } catch (error) {
        console.log('获取商品列表失败', error.message)
        ElMessage.error('获取商品列表失败')
    }
}

// 跳转到商品详情
const goToDetail = (id) => {
    router.push(`/shopping/commodity/${id}`)
}

// 加入购物车
const addToCart = async (commodity) => {
    if (commodity.stock <= 0) {
        ElMessage.warning('商品库存不足')
        return
    }
    
    const cartData = {
        number: 1,
        commodity: commodity.id
    }
    
    try {
        await createCart(cartData)
        ElMessage.success('添加到购物车成功')
    } catch (error) {
        console.log('添加失败', error.message)
        ElMessage.error('添加到购物车失败')
    }
}

// 图片加载错误处理
const handleImageError = (event) => {
    // 隐藏图片，显示占位符
    event.target.style.display = 'none'
    const placeholder = event.target.parentElement.querySelector('.no-image-placeholder')
    if (placeholder) {
        placeholder.style.display = 'flex'
    }
}

// 获取商品图片URL
const getProductImageUrl = (commodity) => {
    if (commodity.commodityimg_set && commodity.commodityimg_set.length > 0 && commodity.commodityimg_set[0].src) {
        // 如果图片路径以 /media/ 开头，直接使用 /file/ 前缀
        if (commodity.commodityimg_set[0].src.startsWith('/media/')) {
            return '/api/' + commodity.commodityimg_set[0].src
        }
        // 否则使用原来的逻辑
        return '/api/' + commodity.commodityimg_set[0].src
    }
    return null
}

// 监听路由变化，重新获取商品列表
watch(() => route.params.id, (newId) => {
    if (newId) {
        fetchCommodityList()
    }
})

// 组件挂载时获取商品列表
onMounted(() => {
    fetchCommodityList()
})
</script>

<style lang="less" scoped>
.product-list-container {
    min-height: 100vh;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    padding: 20px;
}

.content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
}

.header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 20px;
    padding: 30px;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    
    .category-header {
        .category-title {
            font-size: 32px;
            font-weight: 700;
            color: #333;
            margin-bottom: 8px;
        }
        
        .category-subtitle {
            font-size: 16px;
            color: #666;
            margin: 0;
        }
    }
    
    .product-stats {
        .stat-item {
            display: flex;
            align-items: center;
            font-size: 16px;
            color: #667eea;
            font-weight: 600;
            background: rgba(102, 126, 234, 0.1);
            padding: 8px 16px;
            border-radius: 20px;
            
            i {
                margin-right: 8px;
            }
        }
    }
}

.products-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
    gap: 25px;
    
    .product-card {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
        border: 1px solid rgba(255, 255, 255, 0.2);
        transition: all 0.3s ease;
        cursor: pointer;
        
        &:hover {
            transform: translateY(-5px);
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.15);
            
            .product-overlay {
                opacity: 1;
            }
        }
        
        .product-image {
            position: relative;
            height: 200px;
            overflow: hidden;
            
            img {
                width: 100%;
                height: 100%;
                object-fit: cover;
                transition: transform 0.3s ease;
            }
            
            &:hover img {
                transform: scale(1.05);
            }
            
            .no-image-placeholder {
                width: 100%;
                height: 100%;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                background: #f8f8f8;
                color: #999;
                font-size: 14px;
                
                i {
                    font-size: 32px;
                    margin-bottom: 8px;
                }
            }
            
            .product-overlay {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                opacity: 0;
                transition: opacity 0.3s ease;
                
                .add-cart-btn {
                    background: linear-gradient(45deg, #667eea, #764ba2);
                    border: none;
                    border-radius: 20px;
                    padding: 8px 16px;
                    font-size: 14px;
                    
                    &:hover {
                        transform: scale(1.05);
                    }
                }
            }
        }
        
        .product-content {
            padding: 20px;
            
            .product-price {
                font-size: 24px;
                font-weight: 700;
                color: #ff4757;
                margin-bottom: 12px;
            }
            
            .product-name {
                font-size: 16px;
                font-weight: 600;
                color: #333;
                margin-bottom: 12px;
                line-height: 1.4;
                height: 2.8em;
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
            }
            
            .product-meta {
                display: flex;
                justify-content: space-between;
                margin-bottom: 15px;
                
                .meta-item {
                    display: flex;
                    align-items: center;
                    font-size: 12px;
                    color: #666;
                    
                    i {
                        margin-right: 4px;
                    }
                    
                    &.brand {
                        color: #667eea;
                        font-weight: 500;
                    }
                }
            }
            
            .product-actions {
                display: flex;
                justify-content: flex-end;
                
                .stock-tag {
                    border-radius: 12px;
                    font-size: 12px;
                }
            }
        }
    }
}

.empty-state {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 20px;
    padding: 60px;
    text-align: center;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    
    :deep(.el-empty__description) {
        p {
            margin: 5px 0;
            color: #666;
        }
    }
}

// 响应式设计
@media (max-width: 768px) {
    .product-list-container {
        padding: 10px;
    }
    
    .header-section {
        flex-direction: column;
        gap: 20px;
        text-align: center;
        padding: 20px;
        
        .category-header .category-title {
            font-size: 24px;
        }
    }
    
    .products-grid {
        grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
        gap: 15px;
    }
    
    .empty-state {
        padding: 40px 20px;
    }
}

@media (max-width: 480px) {
    .products-grid {
        grid-template-columns: 1fr;
    }
}
</style> 